package icu.lookyousmileface.nio.basic;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

import static java.nio.channels.SelectionKey.OP_READ;

/**
 * @author shenj
 * @title: NettyServer
 * @projectName NettyPro
 * @date 2020/12/1 17:57
 */
public class NioServer {

    public static void main(String[] args) {

        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

            Selector selector = Selector.open();

            serverSocketChannel.socket().bind(new InetSocketAddress(7798));
            //设置未非阻塞
            serverSocketChannel.configureBlocking(false);
            //注册selector，设置关注事件
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

            while (true) {

                if (selector.select(1000) == 0) {
                    System.out.println("超时1s！");
                    continue;
                }
                //selector>0表示触发了关注事件
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();

                iterator.forEachRemaining(s -> {
                    //监听连接事件
                    if (s.isAcceptable()) {
                        try {
                            SocketChannel socketChannel = serverSocketChannel.accept();
                            //非阻塞
                            socketChannel.configureBlocking(false);
                            System.out.println("一个客户端连接成功"+socketChannel.hashCode());
                            socketChannel.register(selector, OP_READ, ByteBuffer.allocate(1024));
                            System.out.println("当前selector中register的channel数量:"+selector.keys().size());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    //监听读事件
                    if (s.isReadable()) {
                        SocketChannel socketChannel = (SocketChannel)s.channel();
                        ByteBuffer dataBuffer = (ByteBuffer)s.attachment();
                        try {
                            socketChannel.read(dataBuffer);
                            System.out.println("来自客户端:"+new String(dataBuffer.array()));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        dataBuffer.clear();
                    }
                    iterator.remove();
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
